package com.jzfai.service;

import com.jzfai.entity.Admin;
import com.jzfai.mapper.AdminMapper;
import com.jzfai.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.ListUtils;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

/**
 * @Title: LoginService
 * @Description:
 * @Auther:Administrator
 * @Version: 1.0
 * @create 2019/8/13 13:41
 */
@Service
public class LoginService {
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    private HttpSession session;

    public JsonData doLogin(Admin admin){
        List<Admin> admins = adminMapper.selectListAdmin(admin);
        if(!admins.isEmpty()){
            //将用户名和密码存储到session中
            session.setAttribute("userInfo",admins.get(0));
            System.out.println("获取session");
            System.out.println(session.getAttribute("userInfo"));
            return JsonData.buildSuccess(admins.get(0));
        }else{
            return  JsonData.buildError("用户名或密码错误");
        }
    }
    public JsonData loginOut(){
        session.setAttribute("userInfo",null);
        return JsonData.buildSuccess();
    }
    public JsonData doAddUser(Admin admin){
        //判断当前用户是否存在
        Admin admin1 = new Admin();
        admin1.setUsername(admin.getUsername());
        List<Admin> admins = adminMapper.selectListAdmin(admin1);
        if(!ListUtils.isEmpty(admins)){
           return JsonData.buildError("用户已存在",35001);
        }else{
            int i = adminMapper.insertAdmin(admin);
            System.out.println("插入用户的数据");
            System.out.println(i);
            return JsonData.buildSuccess();
        }
    }
    public JsonData editUser(Admin admin){
        int i = adminMapper.updateAdmin(admin);
        System.out.println(i);
        if(i!=0){
            return JsonData.buildSuccess();
        }else{
            return JsonData.buildError("更新用户失败",-1);
        }
    }
    public JsonData deleteUser(Integer id){
        int i = adminMapper.deleteByIdAdmin(id);
        if(i>0){
            return JsonData.buildSuccess(null,"删除成功");
        }else{
            return JsonData.buildError("删除用户失败");
        }
    }
    public JsonData getListUser(){
        Admin admin = new Admin();
        admin.setPageNum(0);
        admin.setPageSize(10);
        List<Admin> admins = adminMapper.selectListAdmin(admin);
        HashMap<String , Object> HashMap = new HashMap<>();
        HashMap.put("pageNum",10);
        HashMap.put("total",100);
        HashMap.put("list",admins);
        return JsonData.buildSuccess(HashMap);
    }
}
